package com.magicyuan.search.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;

public class SearchClientHelper {

	private Settings settings;

	private Map<String, Client> clientMap = new ConcurrentHashMap<String, Client>();

	private String clusterName = "elasticsearch-US";

	private SearchClientHelper() {
		init();
	}

	public static final SearchClientHelper getInstance() {
		return ClientHolder.INSTANCE;
	}

	private static class ClientHolder {

		private static final SearchClientHelper INSTANCE = new SearchClientHelper();
	}

	/**
	 * 初始化默认的client
	 */
	public void init() {

		// 设置集群名称
		settings = Settings.builder().put("cluster.name", clusterName)
				.put("xpack.security.user", "transport_client_user:changeme").build();

		addClient(settings);
	}

	public Client getClient() {
		return getClient(clusterName);
	}

	public Client getClient(String clusterName) {
		return clientMap.get(clusterName);
	}

	public void addClient(Settings setting) {
		// 创建client
		TransportClient client = null;
		try {
			client = new PreBuiltXPackTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(
					InetAddress.getByName(PropertiesUtils.getValue("searchAddress")), 9300));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		clientMap.put(setting.get("cluster.name"), client);
	}
}
